package repository

import (
	"fmt"
	"gluenet/modules/manager/server/adapter/repository/mysql"
	"gluenet/modules/manager/server/domain/dependency"
	"gluenet/modules/manager/server/domain/entity"
	"gluenet/modules/manager/server/infra"
	"gluenet/modules/manager/server/infra/prepare"
	"time"
)

func init() {
	prepare.RegisterRepo(func() {
		repo := NewInstanceRepo()
		prepare.InjectDependency(func() dependency.InstanceRepo {
			return repo
		})
	})
}

type Instance struct {
}

func (i *Instance) Add(obj *entity.Instance) (*entity.Instance, error) {
	obj.Created = time.Now()
	obj.Updated = time.Now()
	if _, err := mysql.DB.InsertOne(obj); err != nil {
		return nil, err
	}
	return obj, nil
}

func (i *Instance) Del(ID string, userId string) (*entity.Instance, error) {
	var obj entity.Instance
	_, err := mysql.DB.Where(map[string]interface{}{
		"guid":    ID,
		"user_id": userId,
	}).Delete(&obj)
	if err != nil {
		return nil, err
	}
	return &obj, nil
}

func (i *Instance) Update(obj *entity.Instance) error {
	//TODO implement me
	panic("implement me")
}

func (i *Instance) GetByGuid(GUID string) (*entity.Instance, error) {
	var obj []entity.Instance
	if err := mysql.DB.Where(map[string]interface{}{
		"guid": GUID,
	}).Find(&obj); err != nil {
		return nil, err
	}

	if len(obj) > 1 {
		return nil, fmt.Errorf("much primary keys in sql")
	}

	if len(obj) == 0 {
		return nil, infra.DataNotFind
	}
	//var cfgs = make([]*entity.Config, len(obj))
	//for k, v := range obj {
	//	cfgs[k] = &entity.Config{
	//		Config: v,
	//	}
	//}
	return &obj[0], nil
}

func (i *Instance) Get(GUID string, userID string) (*entity.Instance, error) {
	var obj []entity.Instance
	if err := mysql.DB.Where(map[string]interface{}{
		"guid":    GUID,
		"user_id": userID,
	}).Find(&obj); err != nil {
		return nil, err
	}

	if len(obj) > 1 {
		return nil, fmt.Errorf("much primary keys in sql")
	}

	if len(obj) == 0 {
		return nil, infra.DataNotFind
	}
	//var cfgs = make([]*entity.Config, len(obj))
	//for k, v := range obj {
	//	cfgs[k] = &entity.Config{
	//		Config: v,
	//	}
	//}
	return &obj[0], nil
}

func (i *Instance) FindAll() ([]entity.Instance, error) {
	var obj []entity.Instance
	if err := mysql.DB.Where(map[string]interface{}{}).Find(&obj); err != nil {
		return nil, err
	}
	return obj, nil
}

func (i *Instance) FindBy(query map[string]interface{}) ([]entity.Instance, error) {
	var obj []entity.Instance

	if err := mysql.DB.Where(query).Find(&obj); err != nil {
		return nil, err
	}

	if len(obj) == 0 {
		return nil, fmt.Errorf("can't find data")
	}

	//var cfgs = make([]*entity.Instance, len(obj))
	//for k, v := range obj {
	//	cfgs[k] = &entity.Instance{
	//		Instance: v,
	//	}
	//}
	return obj, nil
}

func NewInstanceRepo() *Instance {
	r := &Instance{}
	return r
}
